﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting;
using System;
using System.IO;
using Zhongjiu.Common;

namespace Zhongjiu.Extensions
{
    public static class SerilogSetup
    {
        /// <summary>
        /// serilog; 日志保存到了seq；
        /// 可直接使用seq
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static void AddSerilogSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            try
            {
                if (Appsettings.app("Logging", "Serilog", "Enabled").ToBool())
                {
                    var serilog = new LoggerConfiguration()
                        .Enrich.WithProperty("Application", Appsettings.app("Startup","ApiName"))//所有日志添加属性Application:zhongjiuApi;
                        .ReadFrom.Configuration(Appsettings.Configuration, "Logging:Serilog");

                    if (Appsettings.app("Logging", "Serilog", "WriteToFile").ToBool())//原生wirteToFile不支持按日志级别分享
                    {
                        //serilog.WriteTo.File(Path.Combine("log", "log.txt"),rollingInterval:RollingInterval.Day,);
                        serilog.WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Debug).WriteTo.File("./Log/Debug/log-Debug-.txt", rollingInterval: RollingInterval.Day))
                                .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Information).WriteTo.File("./Log/Info/log-Info-.txt", rollingInterval: RollingInterval.Day))
                                .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Warning).WriteTo.File("./Log/Warning/log-Warning-.txt", rollingInterval: RollingInterval.Day))
                                .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error || p.Level == LogEventLevel.Fatal).WriteTo.File("./Log/Error/log-Error-.txt", rollingInterval: RollingInterval.Day));
                    }
                    //serilog.Enrich.With()//添加自定义属性；

                    services.AddLogging(loggerBuilder =>
                    {
                        loggerBuilder.AddSerilog(serilog.CreateLogger());
                    });
                }
            }
            catch (Exception e)
            {
                Log.Error("Seq启动失败：", e);
            }
        }
    }
}
